package tk.jfree.example.jooq.controller;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jooq.DSLContext;
import org.jooq.types.UInteger;
import org.jooq.types.ULong;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.jfree.example.jooq.bean.UserDTO;
import tk.jfree.example.jooq.bean.UserVO;
import tk.jfree.example.jooq.codegen.Tables;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Cheng.Wei
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(value = "user")
public class UserController {

    private final DSLContext dslContext;

    @GetMapping
    public ResponseEntity<List<UserVO>> query(){
        List<UserVO> list = dslContext.select().from(Tables.USER).fetchInto(UserVO.class);
        log.debug("查询{}", list);
        return ResponseEntity.ok(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping
    public ResponseEntity add(UserDTO user){
        log.debug("新增DATA:{}", user);
        dslContext.insertInto(Tables.USER)
                .columns(Tables.USER.NAME, Tables.USER.AGE, Tables.USER.GMT_CREATE, Tables.USER.GMT_MODIFIED)
                .values(user.getName(), UInteger.valueOf(user.getAge()), LocalDateTime.now(), LocalDateTime.now()).execute();
        return ResponseEntity.ok("ok");
    }

    @Transactional(rollbackFor = Exception.class)
    @PutMapping(value = "{id}")
    public ResponseEntity  update(@PathVariable long id, UserDTO user){
        log.debug("更新[ID={}], DATA:{}", id, user);
        dslContext.update(Tables.USER)
                .set(Tables.USER.NAME, user.getName())
                .set(Tables.USER.AGE, UInteger.valueOf(user.getAge()))
                .set(Tables.USER.GMT_MODIFIED, LocalDateTime.now())
                .where(Tables.USER.ID.eq(ULong.valueOf(id))).execute();
        return ResponseEntity.ok("update");
    }

    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping(value = "{id}")
    public ResponseEntity delete(@PathVariable long id){
        log.debug("删除[ID={}]", id);
        dslContext.delete(Tables.USER).where(Tables.USER.ID.eq(ULong.valueOf(id))).execute();
        return ResponseEntity.ok("delete");
    }
}
